<template>
  <div class="order_list">
    <van-tabs
      v-model="activeIndex"
      line-width="0"
      title-active-color="#EE3F00"
      title-inactive-color="#111111"
      background="#F8F8F8"
      :swipe-threshold="5"
      @click="handleTabClick"
    >
      <van-tab
        v-for="(tabTitle, index) in tabTitles"
        :title="tabTitle"
        :key="index"
      >
        <van-list
          v-model="loading"
          :finished="finished"
          :immediate-check="false"
          finished-text="没有更多了"
          @load="getOrderList"
        >
          <van-panel
            v-for="(el, i) in orderList"
            :key="i"
            :title="'客户名称: ' + el.name"
            :status="el.orderStatusText"
            @click.native="toOrderDetail(el.id)"
          >
            <div slot="header" style="position: relative; padding: 8px 16px">
              客户名称:{{ el.name }}
              <span
                style="
                  color: #db3d3c;
                  position: absolute;
                  top: 8px;
                  right: 16px;
                "
                >{{ el.orderStatusText }}</span
              >
              <br />
              <span
                style="
                  position: absolute;
                  top: 27px;
                  right: 16px;
                  color: #7d7e80;
                  font-size: 9px;
                  z-index: 100;
                "
                v-show="el.orderStatusText == '订单取消，退款中'"
                >3个工作日内原路退回</span
              >
            </div>
            <van-card
              v-for="(goods, goodsI) in el.goodsList"
              :key="goodsI"
              :title="goods.goodsName"
              :num="goods.number"
              :thumb="goods.picUrl"
            >
              <div slot="desc">
                <div class="desc">
                  <van-tag
                    plain
                    style="margin-right: 6px"
                    v-for="(spec, index) in goods.specifications"
                    :key="index"
                    >{{ el.orderType == 0 ? spec : getSpec(el) }}</van-tag
                  >
                </div>
              </div>
              <div
                slot="footer"
                style="
                  display: flex;
                  width: calc(100vw - 160px);
                  margin-top: 5px;
                "
                v-if="
                  goods.giftGoods !== undefined && goods.giftGoods.length > 0
                "
              >
                <span style="font-weight: bold; color: #000; float: left"
                  >赠品</span
                >
                <div
                  style="
                    margin-left: 6px;
                    display: flex;
                    flex-direction: column;
                    font-size: 11px;
                    width: calc(100% - 30px);
                  "
                >
                  <div
                    style="width: 100%; line-height: 16px"
                    v-for="(gift, index) in goods.giftGoods"
                    :key="index"
                  >
                    <span
                      style="
                        width: calc(100% - 18px);
                        float: left;
                        display: inline-block;
                        text-align: left;
                        display: inline-block;
                        overflow: hidden;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                      "
                    >
                      {{ gift.giftName }}</span
                    >
                    <span style="float: right; margin-left: 5px"
                      >*{{ gift.num * goods.number }}</span
                    >
                  </div>
                </div>
              </div>
            </van-card>
            <div style="margin-left: 15px; margin-top: 5px" v-if="el.shopName">
              下单店铺：{{ el.shopName }}
            </div>
            <div class="total">合计: {{ (el.actualPrice * 100) | yuan }}</div>

            <div slot="footer" class="footer_btn">
              <!-- <van-button
                size="small"
                v-if="el.handleOption.cancel"
                @click.stop="cancelOrder(el.id)"
                disabled
              >查看</van-button>
              <van-button
                size="small"
                v-if="el.handleOption.pay"
                @click.stop="toPay(el.id)"
                disabled
              >查看</van-button> -->
              <!-- <van-button
                size="small"
                v-if="(el.handleOption.commit || el.handleOption.refund) && !el.discountStatus && el.discount > 0"
                type="danger"
                @click.stop="modifyOrder(el.id)"
              >领取优惠</van-button> -->
              <van-button
                size="small"
                v-if="el.handleOption.refund && el.payType != 1"
                type="danger"
                @click.stop="deliveryOrder(el.id)"
                >发货</van-button
              >
              <van-button
                size="small"
                v-else
                @click.stop="confirmOrder(el.id)"
                disabled
                >查看</van-button
              >
              <!-- <van-button
                size="small"
                v-if="el.handleOption.delete"
                @click.stop="delOrder(el.id)"
                disabled
              >查看</van-button>
              <van-button
                size="small"
                v-if="el.handleOption.comment"
                @click.stop="commentOrder(el.id)"
                disabled
              >查看</van-button> -->
            </div>
          </van-panel>
        </van-list>
      </van-tab>
    </van-tabs>
    <van-dialog
      v-model="show"
      title="发货"
      show-cancel-button
      @confirm="onDialogConfirm"
      style="width: 90%"
    >
      <div style="padding: 10px 20px">
        <van-cell-group>
          <van-field
            label="快递公司"
            required
            :readonly="true"
            clickable
            right-icon="arrow"
            :value="deliveryCom"
            placeholder="请选择快递公司"
            @click="onClick"
          />
          <van-field
            label="快递单号"
            clearable
            required
            right-icon="scan"
            v-model="deliverySn"
            placeholder="请输入快递单号"
            size="30px"
            @click-right-icon="scanKd"
          />
        </van-cell-group>
      </div>
    </van-dialog>

    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        @cancel="onCancel"
        @confirm="onConfirm"
      />
    </van-popup>
  </div>
</template>

<script>
import {
  orderList,
  orderDelete,
  orderConfirm,
  orderCancel,
  orderRefund,
  getWxConfig,
  dicItems,
  shipOrder,
  modify,
} from '@/api/api';
import _ from 'lodash';
import {
  Tab,
  Tabs,
  Panel,
  Card,
  List,
  Tag,
  Dialog,
  Field,
  DropdownMenu,
  DropdownItem,
  Row,
  Col,
  Picker,
  Popup,
} from 'vant';

import wx from 'weixin-js-sdk';

export default {
  name: 'order-list-client',

  props: {
    active: {
      type: [String, Number],
      default: 0,
    },
  },
  created() {
    this.init();
  },
  data() {
    return {
      showPicker: false,
      deliverySn: '',
      deliveryCom: '',
      currentOrderId: '',
      columns: [],
      columnsAll: [],
      show: false,
      activeIndex: Number(this.active),
      tabTitles: ['全部', '待付款', '待发货', '待收货', '已完成'],
      serveId: -1,
      orderList: [],
      page: 0,
      limit: 10,
      loading: false,
      finished: false,
    };
  },

  methods: {
    getSpec(el) {
      if (el.payType == 1) {
        return '试机';
      } else if (el.payType == 2) {
        return '定金';
      } else if (el.payType == 3) {
        return '全款';
      }
    },
    onDialogConfirm() {
      if (this.deliverySn == '') {
        alert('请输入快递单号');
        return;
      }
      if (this.deliveryCom == '') {
        alert('请选择快递公司');
        return;
      }
      shipOrder({
        orderId: this.currentOrderId,
        shipSn: this.deliverySn,
        shipChannel: this.deliveryCom,
      }).then((res) => {
        this.page = 0;
        this.orderList = [];
        this.getOrderList();
      });
    },
    scanKd() {
      let that = this;
      wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
        success: function (res) {
          //var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
          // alert(JSON.stringify(res));
          // alert('11111222222');
          let AarrydeliverySn = res.resultStr.split(',');
          if (AarrydeliverySn.length > 1) {
            that.deliverySn = AarrydeliverySn[1];
          } else {
            that.deliverySn = AarrydeliverySn[0];
          }
        },
      });
    },
    onClick() {
      //console.log('click');
      this.showPicker = true;
      //this.show = false;
    },
    onCancel() {
      this.showPicker = false;
      //this.show = true;
    },
    onConfirm(value) {
      this.deliveryCom = value;
      //console.log(this.deliveryCom);
      this.showPicker = false;
      if (value == '自提') {
        this.deliverySn = 'zt0001';
      }
      //this.show = true;
    },
    init() {
      this.page = 0;
      this.orderList = [];
      this.getOrderList();
      // 获取字典表数据
      dicItems({ groupId: 'ORDER.KD.CLASS' })
        .then((res) => {
          this.columnsAll = res.data.data.list;
          if (this.columnsAll != null) {
            for (let i = 0; i < this.columnsAll.length; i++) {
              this.columns[i] = this.columnsAll[i].itemName;
            }
          }
        })
        .catch(() => {});
      //console.log(location.href.split('#')[0]);
      getWxConfig({ url: location.href.split('#')[0] }).then((res) => {
        wx.config({
          // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          debug: false,
          // 必填，公众号的唯一标识
          appId: res.data.data.appId,
          // 必填，生成签名的时间戳
          timestamp: res.data.data.timestamp,
          // 必填，生成签名的随机串
          nonceStr: res.data.data.nonceStr,
          // 必填，签名，见附录1
          signature: res.data.data.signature,
          // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
          jsApiList: ['checkJsApi', 'scanQRCode'],
        });
      });

      wx.error(function (res) {
        alert('出错了：' + res.errMsg); //这个地方的好处就是wx.config配置错误，会弹出窗口哪里错误，然后根据微信文档查询即可。
      });
      wx.ready(function () {
        wx.checkJsApi({
          jsApiList: ['scanQRCode'],
          success: function (res) {
            //alert('成功了：' + res.errMsg);
          },
        });
      });
    },
    getOrderList() {
      this.page++;
      orderList({
        showType: this.activeIndex,
        type: 2,
        page: this.page,
        limit: this.limit,
      }).then((res) => {
        this.orderList.push(...res.data.data.list);
        this.loading = false;
        this.finished = res.data.data.page >= res.data.data.pages;
      });
    },
    delOrder(id) {
      let that = this;
      this.$dialog
        .confirm({ message: '确定要删除该订单吗?' })
        .then(() => {
          orderDelete({ orderId: id }).then(() => {
            this.init();
            this.$toast('已删除订单');
          });
        })
        .catch(() => {});
    },
    // 修改订单id
    modifyOrder(id) {
      modify({ orderId: id })
        .then((res) => {
          this.page = 0;
          this.orderList = [];
          this.getOrderList();
        })
        .catch();
    },
    // 发货
    deliveryOrder(id) {
      this.currentOrderId = id;
      this.show = true;
    },
    cancelOrder(id) {
      this.$dialog
        .confirm({ message: '确定要取消该订单吗?' })
        .then(() => {
          orderCancel({ orderId: id }).then(() => {
            this.init();
            this.$toast('已取消该订单');
          });
        })
        .catch(() => {});
    },
    refundOrder(id) {
      this.$dialog
        .confirm({ message: '确定要申请退款吗?' })
        .then(() => {
          orderRefund({ orderId: id }).then(() => {
            this.init();
            this.$toast('已申请订单退款');
          });
        })
        .catch(() => {});
    },
    confirmOrder(id) {
      this.$dialog
        .confirm({
          message: '请确认收到货物, 确认收货后无法撤销!',
        })
        .then(() => {
          orderConfirm({ orderId: id }).then(() => {
            this.init();
            this.$toast('已确认收货');
          });
        })
        .catch(() => {});
    },
    commentOrder(id) {},
    handleTabClick() {
      this.page = 0;
      this.orderList = [];
      this.getOrderList();
    },
    toOrderDetail(id) {
      this.$router.push({
        path: '/order/order-detail-client',
        query: { orderId: id },
      });
    },
  },
  components: {
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Panel.name]: Panel,
    [Card.name]: Card,
    [List.name]: List,
    [Tag.name]: Tag,
    [Field.name]: Field,
    [Row.name]: Row,
    [Col.name]: Col,
    [Picker.name]: Picker,
    [Popup.name]: Popup,
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
    [Dialog.Component.name]: Dialog.Component,
  },
};
</script>

<style lang="scss" scoped>
/deep/ .van-tabs__nav--line {
  position: fixed;
  z-index: 100;
  padding-bottom: 0;
  height: 44px;
  width: 100%;
}
.van-tabs__nav {
  margin: 0;
}
.order_list {
  .van-panel {
    margin-top: 20px;
  }

  .van-card {
    background-color: #fff;
    .van-card__footer {
      padding-left: 98px;
    }
  }

  .total {
    text-align: right;
    padding: 10px;
  }

  .footer_btn {
    text-align: right;
    .van-button {
      margin-left: 10px;
    }
  }
}
</style>
